package com.puff.jdbc.core;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * XML解析
 * @author dongchao
 *
 */
public class NodeParser {

	public Document parser(InputStream in) {
		return createDocument(in);
	}

	public String attr(Node node, String key) {
		Node attr = node.getAttributes().getNamedItem(key);
		if (attr == null) {
			return "";
		}
		return attr.getNodeValue();
	}

	private Document createDocument(InputStream in) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		factory.setNamespaceAware(false);
		factory.setIgnoringComments(true);
		factory.setIgnoringElementContentWhitespace(false);
		factory.setCoalescing(false);
		factory.setExpandEntityReferences(true);
		try {
			return factory.newDocumentBuilder().parse(in);
		} catch (Exception e) {
			throw new RuntimeException("XML parse error！", e);
		}
	}

}
